package threading;

/**
 * @author krystal
 * @date 2022/11/23 11:35
 */
//演示线程安全问题
class Counter{
    public int count=0;
//    public synchronized void increase(){
//        count++;
//    }
    //写法一
    public void increase(){
        synchronized (this){
            count++;
        }
    }
    //写法二
//    public Object locker=new Object();
//    public void increase(){
//        synchronized (locker){
//            count++;
//        }
//    }
    //写法三
//    public static Locker locker=new Locker();
//        public void increase(){
//            synchronized (locker){
//                count++;
//            }
//        }
    }

public class Demo14 {
    private static Counter counter=new Counter();

    public static void main(String[] args) throws InterruptedException {
        //两个线程，每个线程都针对count进行5w的自增
        //预期结果10w
        Thread t1=new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });
        Thread t2=new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });
        t1.start();
        t2.start();

        t1.join();
        t2.join();
        System.out.println("counter:"+counter.count);
    }
}
